package org.rain.common.util.json.status;

import org.rain.common.util.json.AbsJsonState;
import org.rain.common.util.json.JsonFsm;

/**
 * created by yangtong on 2025/4/14 22:41:56
 * <br/>
 * 表示正在读取bool、null或者一些其他特定字面量类型的value
 */
public class InLiteralValueState extends AbsJsonState {
    @Override
    public void handleNonWhitespace(JsonFsm fsm, char c) {
        fsm.writeBuffer();
        int matchedLength = fsm.getBufferLength();
        String targetLiteral = fsm.currentTargetLiteral();
        //如果当前buffer的长度超过了目标字符串，或者buffer的前面部分和目标字符串不匹配，则说明当前value不符合预期，报错
        if (matchedLength > targetLiteral.length()
                || !targetLiteral.regionMatches(true, 0, fsm.getBuffer(), 0, matchedLength)) {
            throw new RuntimeException("无效的字面值: " + fsm.getBuffer());
        }
        //完整字面值已读完
        if (matchedLength == targetLiteral.length()) {
            Object value;
            if ("true".equals(targetLiteral)) {
                value = Boolean.TRUE;
            } else if ("false".equals(targetLiteral)) {
                value = Boolean.FALSE;
            } else if ("null".equals(targetLiteral)) {
                value = null;
            } else {
                throw new RuntimeException("未知字面量：" + targetLiteral);
            }
            fsm.acceptValue(value);
            fsm.targetLiteral(null);
            fsm.changeState(EXPECT_COMMA_OR_END);
        }
    }
}
